﻿using Core.Persistence.Interceptors;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Infrastructure.Persistence.EventHandler;

public class AuditPublishedEventHandler(
    ILogger<AuditPublishedEventHandler> logger,
    IdentityDbContext context) 
    : INotificationHandler<AuditPublishedEvent>
{
    public async Task Handle(AuditPublishedEvent notification, CancellationToken cancellationToken)
    {
        if (context == null) return;
        try
        {
            await context.AuditTrails.AddRangeAsync(notification.Trails!, cancellationToken);
            await context.SaveChangesAsync(cancellationToken);
        }
        catch
        {
            logger.LogError("error while saving audit trail");
        }
        return;
    }
}
